<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div v-show="!showMaterialDetail" class="p-4 interface-display">
    <el-card shadow="hover" style="margin-bottom: 10px">
      <el-form :inline="true" size="small" label-width="80px">
        <el-form-item label="要素库类型">
          <el-cascader
            ref="cascader"
            v-model="path"
            :options="modelTreeCopy"
            placeholder="请选择"
            :props="cascaderProps"
            @change="handleCascaderChange"
          />
        </el-form-item>

        <el-form-item label="业务场景">
          <el-select v-model="queryParams.sceneId" placeholder="请选择" style="width: 240px" clearable @change="handleSelectScenariosChange">
            <el-option v-for="item in businessScenariosList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="业务系统">
          <el-select v-model="queryParams.systemId" placeholder="请选择" style="width: 240px" clearable @change="handleSelectSystemsChange">
            <el-option v-for="item in businessSystemList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="模型名称">
          <el-select v-model="queryParams.modelId" placeholder="请选择" style="width: 240px" clearable>
            <el-option v-for="item in modelList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="发布状态">
          <el-select v-model="queryParams.status" placeholder="请选择" style="width: 240px" clearable>
            <el-option label="待发布" value="0"></el-option>
            <el-option label="已发布" value="1"></el-option>
            <el-option label="已撤销" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="创建人">
          <el-input v-model="queryParams.createBy" placeholder="请输入创建人" style="width: 240px" clearable />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRangeCreateTime"
            style="width: 240px"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="发布时间">
          <el-date-picker
            v-model="dateRangeReleaseTime"
            style="width: 240px"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          ></el-date-picker>
        </el-form-item>

        <el-form-item style="margin-left: 80px">
          <el-button size="small" type="primary" icon="search" @click="doQuery">查询</el-button>
          <el-button size="small" type="default" icon="refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-tabs v-model="activeName" @tab-change="handleTabChange">
      <el-tab-pane label="数据调用服务" name="数据调用服务">
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="6">
                <el-button size="small" type="primary" plain icon="plus" @click="buttonClick('add', null)">数据调用服务</el-button>
              </el-col>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="metaList" style="width: 100%">
            <el-table-column label="序号" align="left" type="index" width="50" fixed="left" />
            <el-table-column label="服务名称" align="left" prop="serverName" width="150" fixed="left" />
            <el-table-column label="要素库" align="left" prop="databaseTypeName" />
            <el-table-column label="业务场景" align="left" prop="sceneName" />
            <el-table-column label="业务系统" align="left" prop="systemName" />
            <el-table-column label="模型&版本" align="left">
              <template #default="scope"> {{ scope.row.modelName }}/{{ scope.row.modelVersion }} </template>
            </el-table-column>
            <el-table-column label="发布状态" align="left" prop="status">
              <template #default="scope">
                {{ scope.row.status === 0 ? '待发布' : scope.row.status === 1 ? '已发布' : '已撤销' }}
              </template>
            </el-table-column>
            <el-table-column label="发布时间" align="left" prop="releaseTime" />
            <el-table-column label="服务次数" align="left" prop="serviceTimes" />
            <el-table-column label="创建人" align="left" prop="createBy" />
            <el-table-column label="创建时间" align="left" prop="createTime" />
            <el-table-column label="服务描述" align="left" prop="description" width="200" />
            <el-table-column label="操作" align="left" width="400" fixed="right">
              <template #default="scope">
                <el-button size="small" link type="primary" @click="buttonClick('viewData', scope.row)">查看数据</el-button>
                <el-button size="small" link type="primary" @click="buttonClick('view', scope.row)">详情</el-button>
                <el-button :disabled="scope.row.status === 1 ? true : false" size="small" link type="primary" @click="buttonClick('edit', scope.row)"
                  >编辑</el-button
                >
                <el-button v-if="[0, 2].includes(scope.row.status)" size="small" link type="primary" @click="buttonClick('publish', scope.row)"
                  >发布</el-button
                >
                <el-button v-if="scope.row.status === 1" size="small" link type="primary" @click="buttonClick('cancel', scope.row)"> 撤销 </el-button>
                <el-button
                  :disabled="scope.row.status === 1 ? true : false"
                  size="small"
                  link
                  type="primary"
                  @click="buttonClick('delete', scope.row)"
                  >删除</el-button
                >
                <el-button size="small" link type="primary" @click="buttonClick('viewServiceAddress', scope.row)">服务地址 </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="数据存储服务" name="数据存储服务">
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="6">
                <el-button size="small" type="primary" plain icon="plus" @click="buttonClick('add', null)">数据存储服务</el-button>
              </el-col>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="metaList" style="width: 100%">
            <el-table-column label="序号" align="left" type="index" width="50" fixed="left" />
            <el-table-column label="服务名称" align="left" prop="serverName" width="150" fixed="left" />
            <el-table-column label="要素库" align="left" prop="databaseTypeName" />
            <el-table-column label="业务场景" align="left" prop="sceneName" />
            <el-table-column label="业务系统" align="left" prop="systemName" />
            <el-table-column label="模型&版本" align="left">
              <template #default="scope"> {{ scope.row.modelName }}/{{ scope.row.modelVersion }} </template>
            </el-table-column>
            <el-table-column label="发布状态" align="left" prop="status">
              <template #default="scope">
                {{ scope.row.status === 0 ? '待发布' : scope.row.status === 1 ? '已发布' : '已撤销' }}
              </template>
            </el-table-column>
            <el-table-column label="发布时间" align="left" prop="releaseTime" />
            <el-table-column label="服务次数" align="left" prop="serviceTimes" />
            <el-table-column label="创建人" align="left" prop="createBy" />
            <el-table-column label="创建时间" align="left" prop="createTime" />
            <el-table-column label="服务描述" align="left" prop="description" width="200" />
            <el-table-column label="操作" align="left" width="400" fixed="right">
              <template #default="scope">
                <el-button size="small" link type="primary" @click="buttonClick('viewData', scope.row)">查看数据</el-button>
                <el-button size="small" link type="primary" @click="buttonClick('view', scope.row)">详情</el-button>
                <el-button :disabled="scope.row.status === 1 ? true : false" size="small" link type="primary" @click="buttonClick('edit', scope.row)"
                  >编辑</el-button
                >
                <el-button v-if="[0, 2].includes(scope.row.status)" size="small" link type="primary" @click="buttonClick('publish', scope.row)"
                  >发布</el-button
                >
                <el-button v-if="scope.row.status === 1" size="small" link type="primary" @click="buttonClick('cancel', scope.row)"> 撤销 </el-button>
                <el-button
                  :disabled="scope.row.status === 1 ? true : false"
                  size="small"
                  link
                  type="primary"
                  @click="buttonClick('delete', scope.row)"
                  >删除</el-button
                >
                <el-button size="small" link type="primary" @click="buttonClick('viewServiceAddress', scope.row)">服务地址 </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <div class="pagenation">
      <pagination
        v-show="total > 0"
        style="margin-top: 0;"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        :background="false"
        layout="total, sizes, prev, pager, next, jumper"
        @pagination="handleCurrentChange"
      />
    </div>
  </div>
  <addServices
    v-if="addDialogVisible"
    :add-dialog-visible="addDialogVisible"
    :operate-type="operateType"
    :server-type="serverType"
    :row-data="rowData"
    @handle-event="handleEvent"
  />
  <viewService
    v-if="viewDialogVisible"
    :view-dialog-visible="viewDialogVisible"
    :row-data="rowData"
    :operate-type="operateType"
    :show-detail="showDetail"
    @handle-event="handleEvent"
  />
  <MaterialPage v-if="showMaterialDetail" type="tabContent" param="dataService" :row-data="rowData" @handle-event="handleEvent" />
</template>

<script setup>
import addServices from './components/addServices.vue';
import viewService from './components/viewService.vue';
import MaterialPage from '@/views/material/component/MaterialPage.vue';
import { getDataServicesList, deleteDataServices, publishDataServices, revokeDataServices } from '@/api/dataServices/index.ts';
import { getModellTree, getModellTreeByBusiness } from '@/api/metaData/model.ts';
const showMaterialDetail = ref(false);
const showDetail = ref(false);
const dateRangeCreateTime = ref([]);
const dateRangeReleaseTime = ref([]);
const businessScenariosList = ref([]);
const businessSystemList = ref([]);
const treeData = ref([]);
const modelList = ref([]);
const path = ref([]);
const cascader = ref();
const cascaderProps = ref({
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: true
});
const modelPath = ref([]);
const modelTree = ref([]);
const modelTreeCopy = ref([]);
const addDialogVisible = ref(false);
const viewDialogVisible = ref(false);
const operateType = ref('');
const activeName = ref('数据调用服务');
const metaList = ref([]);
const serverType = ref(0);
const loading = ref(false);
const total = ref(2);
const rowData = ref({});
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  orderByColumn: null,
  databaseTypeId: null,
  sceneId: null,
  systemId: null,
  status: null,
  serverType: 0,
  releaseTimeStart: '',
  releaseTimeEnd: '',
  createTimeStart: '',
  createTimeEnd: '',
  createBy: ''
});
// 监听要素数据库,业务场景和业务系统的变化
const updateModelLists = () => {
  queryParams.value.modelId = '';
  modelList.value = [];
  const { databaseTypeId, sceneId, systemId } = queryParams.value;
  if (databaseTypeId && sceneId) {
    getModellTreeByBusiness({ databaseTypeId, sceneId, systemId }).then((response) => {
      if (response.code === 200) {
        modelList.value = response.data?.children || [];
      }
    });
  } else {
    modelList.value = [];
  }
};

watch(() => [queryParams.value.databaseTypeId, queryParams.value.sceneId, queryParams.value.systemId], updateModelLists, { immediate: true });

// 获取要素库节点数据
const findDatabaseBussisinessIdByIds = (nodes, ids) => {
  for (const node of nodes) {
    if (node.id === ids[ids.length - 1]) {
      return node;
    }
    if (node.children) {
      const foundNode = findDatabaseBussisinessIdByIds(node.children, ids);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
};

// 绑定数据库
const handleCascaderChange = (valueArr) => {
  queryParams.value.sceneId = '';
  queryParams.value.systemId = '';
  modelList.value = [];
  queryParams.value.modelId = '';
  cascader.value.togglePopperVisible(false);
  const foundNode = findDatabaseBussisinessIdByIds([treeData.value], valueArr);
  if (foundNode) {
    // 处理树结构，筛选出业务场景树结构
    queryParams.value.databaseTypeId = foundNode.businessId;
    const filterBusinessScenariosList = foundNode.children.map((node) => filterBusinessScenarios(node)).filter((node) => node !== null);
    businessScenariosList.value = filterBusinessScenariosList.map((node) => ({
      id: node.businessId,
      name: node.name,
      type: node.type,
      children: node.children
    }));
  }
};
// 绑定业务场景
const handleSelectScenariosChange = (value) => {
  queryParams.value.systemId = '';
  modelList.value = [];
  queryParams.value.modelId = '';
  const selectedNode = businessScenariosList.value.find((item) => item.id === value);
  queryParams.value.sceneId = selectedNode.id;
  const filterBusinessSystemsList = selectedNode.children.map((node) => filterBusinessSystems(node)).filter((node) => node !== null);
  businessSystemList.value = filterBusinessSystemsList.map((node) => ({
    id: node.businessId,
    name: node.name,
    type: node.type,
    children: node.children
  }));
};
const handleSelectSystemsChange = () => {
  modelList.value = [];
  queryParams.value.modelId = '';
};

// 处理树结构，筛选出业务场景库树结构
const filterBusinessScenarios = (node) => {
  if (node.type === 'scene') {
    const newNode = { id: node.id, businessId: node.businessId, name: node.name, type: node.type, children: node.children };
    return newNode;
  }
  return null;
};
// 处理树结构，筛选出业务系统树结构
const filterBusinessSystems = (node) => {
  if (node.type === 'system') {
    const newNode = { id: node.id, businessId: node.businessId, name: node.name, type: node.type, children: node.children };
    return newNode;
  }
  return null;
};

const handleTabChange = (newTab) => {
  activeName.value = newTab;
  queryParams.value.serverType = newTab === '数据调用服务' ? 0 : 1;
  queryParams.value.pageNum = 1;
  getList();
};
const handleCurrentChange = () => {
  getList();
};

const buttonClick = (type, row) => {
  if (type === 'add') {
    addDialogVisible.value = true;
    serverType.value = queryParams.value.serverType;
    operateType.value = 'add';
  }
  if (type === 'viewData') {
    rowData.value = {
      id: row.id,
      modelId: row.modelId,
      serverType: row.serverType
    };
    showMaterialDetail.value = true;
    console.log('rowData.value', rowData.value);
  }
  if (type === 'viewHistoryData') {
    rowData.value = row;
    showMaterialDetail.value = true;
    showDetail.value = false;
    console.log('rowData.value', rowData.value);
  }
  if (type === 'view') {
    rowData.value = row;
    viewDialogVisible.value = true;
    showDetail.value = true;
    operateType.value = 'view';
  }
  if (type === 'edit') {
    rowData.value = row;
    addDialogVisible.value = true;
    operateType.value = 'edit';
  }
  if (type === 'publish') {
    ElMessageBox.confirm('确定发布该服务？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      publishDataServices({ id: row.id }).then((res) => {
        if (res.code === 200) {
          ElMessage.success('发布成功');
          resetQuery();
        }
      });
    });
  }
  if (type === 'cancel') {
    ElMessageBox.confirm('确定撤销该服务？撤销后将无法为用户提供服务！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      revokeDataServices({ id: row.id }).then((res) => {
        if (res.code === 200) {
          ElMessage.success('撤销成功');
          resetQuery();
        }
      });
    });
  }
  if (type === 'delete') {
    ElMessageBox.confirm('确定删除该服务？删除后将无法恢复！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteDataServices(row.id).then((res) => {
        if (res.code === 200) {
          ElMessage.success('删除成功');
          resetQuery();
        }
      });
    });
  }
  if (type === 'viewServiceAddress') {
    rowData.value = row;
    viewDialogVisible.value = true;
    showDetail.value = true;
    operateType.value = 'viewServiceAddress';
  }
};
const handleEvent = (data) => {
  if (data.type === 'viewHistoryData') {
    buttonClick('viewHistoryData', data.params);
  } else if (data.param === 'dataService') {
    showMaterialDetail.value = false;
    if (viewDialogVisible.value) {
      showDetail.value = true;
    }
  } else {
    showMaterialDetail.value = false;
    addDialogVisible.value = false;
    serverType.value = 0;
    operateType.value = '';
    rowData.value = {};
    viewDialogVisible.value = false;
    showDetail.value = false;
    resetQuery();
  }
};
const resetQuery = () => {
  dateRangeCreateTime.value = ['', ''];
  dateRangeReleaseTime.value = ['', ''];
  modelPath.value = [];
  path.value = [];
  activeName.value = '数据调用服务';
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    databaseTypeId: '',
    sceneId: '',
    systemId: '',
    status: '',
    serverType: 0,
    releaseTimeStart: '',
    releaseTimeEnd: '',
    createTimeStart: '',
    createTimeEnd: '',
    createBy: ''
  };
  getList();
};

const doQuery = () => {
  getList();
};

// 获取级联选择器节点数据
const findNodeByIds = (nodes, ids) => {
  for (const node of nodes) {
    if (node.id === ids[ids.length - 1]) {
      return node;
    }
    if (node.children) {
      const foundNode = findNodeByIds(node.children, ids);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
};

// 筛选出要素库树结构
function filterTreeDatasource(nodes) {
  return nodes.reduce((acc, node) => {
    if (node.type === 'database_1' || node.type === 'database_2') {
      // 递归处理子节点
      if (node.children && node.children.length > 0) {
        node.children = filterTreeDatasource(node.children);
      }
      acc.push(node);
    } else if (node.children && node.children.length > 0) {
      // 如果不是目标节点类型，但有子节点，递归处理子节点，并将符合条件的子节点添加到当前节点
      const filteredChildren = filterTreeDatasource(node.children);
      if (filteredChildren.length > 0) {
        acc.push({ ...node, children: filteredChildren });
      }
    }
    return acc;
  }, []);
}

const getList = () => {
  loading.value = true;
  queryParams.value.createTimeStart = new Date(dateRangeCreateTime.value[0]).getTime();
  queryParams.value.createTimeEnd = new Date(dateRangeCreateTime.value[1]).getTime();
  queryParams.value.releaseTimeStart = new Date(dateRangeReleaseTime.value[0]).getTime();
  queryParams.value.releaseTimeEnd = new Date(dateRangeReleaseTime.value[1]).getTime();
  getDataServicesList(queryParams.value).then((res) => {
    if (res.code === 200) {
      metaList.value = res.data.records;
      total.value = res.data.total;
    }
    loading.value = false;
  });
  const params = {
    pageSize: 9999,
    pageNum: 1
  };
  getModellTree(params).then((res) => {
    if (res.code === 200) {
      treeData.value = res.data;
      modelTree.value = filterTreeDatasource([JSON.parse(JSON.stringify(res.data))]);
      modelTreeCopy.value = JSON.parse(JSON.stringify(modelTree.value));
    }
  });
};
onMounted(() => {
  getList();
  updateModelLists();
});
</script>

<style lang="scss" scoped>
.interface-display {
  height: calc(100vh - 84px);
  overflow: auto;
}

.pagenation {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
